package com.artifex.mupdf.viewer

import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment

class PatternEditorDialog(
    private val pattern: SentencePattern? = null,
    private val onSave: (SentencePattern) -> Unit
) : DialogFragment() {

    private lateinit var nameInput: EditText
    private lateinit var regexInput: EditText
    private lateinit var descriptionInput: EditText
    private lateinit var testResult: TextView
    private lateinit var testResultLabel: TextView

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val builder = AlertDialog.Builder(requireContext())
            .setTitle(if (pattern == null) "Add New Pattern" else "Edit Pattern")

        val view = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_pattern_editor, null)
        builder.setView(view)

        nameInput = view.findViewById(R.id.nameInput)
        regexInput = view.findViewById(R.id.regexInput)
        descriptionInput = view.findViewById(R.id.descriptionInput)
        testResult = view.findViewById(R.id.testResult)
        testResultLabel = view.findViewById(R.id.testResultLabel)

        val testButton = view.findViewById<Button>(R.id.testButton)
        val cancelButton = view.findViewById<Button>(R.id.cancelButton)
        val saveButton = view.findViewById<Button>(R.id.saveButton)

        // Pre-fill fields if editing existing pattern
        pattern?.let {
            nameInput.setText(it.name)
            regexInput.setText(it.regex)
            descriptionInput.setText(it.description)
        }

        testButton.setOnClickListener {
            val testText = "This is a test sentence. Does it work? Yes, it does!\n\nNew paragraph."
            val pattern = regexInput.text.toString()

            try {
                val result = testText.split(pattern.toRegex())
                testResult.text = result.joinToString("\n\n---\n\n")
                testResult.visibility = View.VISIBLE
                testResultLabel.visibility = View.VISIBLE
            } catch (e: Exception) {
                testResult.text = "Invalid pattern: ${e.message}"
                testResult.visibility = View.VISIBLE
                testResultLabel.visibility = View.VISIBLE
            }
        }

        cancelButton.setOnClickListener {
            dismiss()
        }

        saveButton.setOnClickListener {
            val name = nameInput.text.toString().takeIf { it.isNotBlank() } ?: "Unnamed Pattern"
            val regex = regexInput.text.toString()

            if (regex.isBlank()) {
                Toast.makeText(requireContext(), "Regex pattern cannot be empty", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            try {
                // Validate the regex
                regex.toRegex()

                val newPattern = pattern?.copy(
                    name = name,
                    regex = regex,
                    description = descriptionInput.text.toString()
                ) ?: SentencePattern(
                    name = name,
                    regex = regex,
                    description = descriptionInput.text.toString(),
                    order = 0
                )

                onSave(newPattern)
                dismiss()
            } catch (e: Exception) {
                Toast.makeText(requireContext(), "Invalid regex pattern: ${e.message}", Toast.LENGTH_LONG).show()
            }
        }

        return builder.create()
    }
}